﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using VIB.View;
using System.Data;
using System.Timers;
using System.Net.Mail;
using VIB.Model;

namespace VIB
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        Timer mailTimer = new Timer(300000.0);

        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            RefreshControlStatus();

            try
            {
                DataManager.OpenConnection();
            }
            catch (Exception ex)
            {
            
                MessageBox.Show(ex.ToString());
            }
           
            mailTimer.Elapsed +=new ElapsedEventHandler(mailTimer_Elapsed);
            mailTimer.Start();
        }

        void  mailTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            foreach (MailReminder item in DataManager.GetMailReminders())
            {
                MailMessage mail = new MailMessage();

                //add admins to CC
                foreach (string adminMail in DataManager.GetAdminEmails())
                {
                    mail.CC.Add(adminMail);
                }
                mail.From = new MailAddress("abesender@email.de");
                mail.To.Add(item.Email);
                mail.Subject = "Erinnerung: Buchrückgabe";
                mail.Body = "Sie hatten bis zum: " + item.ReturnUntil.ToShortDateString() + " das Buch " + item.Title + " ausgeliehen.\r\n\r\n" +

               "Bitte das Buch zeitnah zurück bringen\r\n\r\n\r\nAutomatisierte Nachricht der Vanderlande Industries Bibliothek";

                Mailer.SendMail(mail);

                DataManager.UpdateMailSent(item.idOwnership);
            }
        }

        private void AddBook(object sender, RoutedEventArgs e)
        {
            AddBook window_addBook = new AddBook();
            window_addBook.Owner = this;
            window_addBook.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterOwner;
            window_addBook.ShowDialog();
            RefreshControlStatus();
        }

        public void RefreshControlStatus()
        {
            try
            {
                dataGrid_books.ItemsSource = DataManager.GetBooks().DefaultView;
                dataGrid_books.SelectedItem = null;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            
        }

        private void RemoveBook(object sender, RoutedEventArgs e)
        {
            if (dataGrid_books.SelectedItems.Count > 0)
            {
                DataRowView row = (DataRowView)dataGrid_books.SelectedItem;

                int idBook = (int)row["idbook"];

                if(MessageBox.Show((string)row["title"] + "\nwirklich aus der Datenbank entfernen?", "Wirklich löschen?", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                {
                      DataManager.DeleteBook(idBook);
                }              

                RefreshControlStatus();
            }
            else
            {
                MessageBox.Show("Bitte wählen sie ein Buch aus der Liste aus");
            }

        }

        private void AddOwnerShip(object sender, RoutedEventArgs e)
        {
            GetInfo info = new GetInfo();
            info.Owner = this;
            info.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterOwner;
            info.ShowDatePicker = true;
            info.ShowDialog();

            if (info.DialogResult == true)
            {
                try
                {
                    DataManager.AddOwnerShip(info.UserId, info.Isbn, info.ReturnDate);
                }
                catch (Exception ex)
                {
                    if (ex.Message == "BookNotAvailiable")
                    {
                        MessageBox.Show("Buch nicht bekannt oder bereits ausgeliehen");
                    }
                    else
                    {
                        MessageBox.Show(ex.ToString());
                    }
                }                
            }
            RefreshControlStatus();
        }

        private void ReturnBook(object sender, RoutedEventArgs e)
        {
            GetInfo info = new GetInfo();
            info.Owner = this;
            info.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterOwner;
            info.ShowDialog();

            if (info.DialogResult == true)
            {
                try
                {
                    DataManager.ReturnBook(info.UserId, info.Isbn);
                }
                catch(Exception ex)
                {
                    if (ex.Message == "BookNotInDataBase")
                    {
                        MessageBox.Show("Buch wurde nicht in der Datenbank gefunden. \nBitte vom Bibliothekar einpflegen lassen.");
                    }
                }
                
            }

            RefreshControlStatus();
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            
            if (Scanner.Instance.Port.IsOpen)
            {
                Scanner.Instance.Port.Close();
            }

            DataManager.CloseConnection();
                      
        }

        private void OpenUserManagement(object sender, RoutedEventArgs e)
        {

            UserManagement userManagement = new UserManagement();
            userManagement.Owner = this;
            userManagement.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterOwner;
            userManagement.Show();
        }

        private void dataGrid_books_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            DataRowView row = (DataRowView)dataGrid_books.SelectedItem;

            int idBook = (int)row["idbook"];
            string isbn = (string)row["isbn"];
            string title = (string)row["title"];
            string author = (string)row["author"];
            int year = (int)row["year"];


            BookInfo bookInfo = new BookInfo(idBook, isbn, author, title, year);
            bookInfo.Owner = this;
            bookInfo.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterOwner;
            bookInfo.Show();
        }

        private void Login(object sender, RoutedEventArgs e)
        {
            AdminLogin login = new AdminLogin();

            login.Owner = this;
            login.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterOwner;

            if (login.ShowDialog() == true)
            {
                button_login.Visibility = Visibility.Collapsed;
                button_logout.Visibility = Visibility.Visible;
                button_AddBook.Visibility = Visibility.Visible;
                button_RemoveBook.Visibility = Visibility.Visible;
                button_usermanagement.Visibility = Visibility.Visible;
            }
        }

        private void Logout(object sender, RoutedEventArgs e)
        {
            button_login.Visibility = Visibility.Visible;
            button_logout.Visibility = Visibility.Hidden;
            button_AddBook.Visibility = Visibility.Hidden;
            button_RemoveBook.Visibility = Visibility.Hidden;
            button_usermanagement.Visibility = Visibility.Hidden;
        }
    }
}
